<?php

class DichvuController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column1';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			//'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array(''),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array( 'muadichvu','muadichvu2','muadichvu3', 'history','suggestDichvu','getJson'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('view','create','update','index','admin','delete','orderadmin','exportorder', 'gia','listgiauser', 'tracode', 'xoa', 'quickaccess',
			 'historyuser','historyuseradmin','completeuser','xoagiauser'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}
	
	/**
	 * Xoa gia uu dai cua user
	 * Enter description here ...
	 */
	public function actionXoaGiaUser(){
		if( isset($_REQUEST['iduser']) && isset($_REQUEST['iddichvu']) ){
			$giauser = GiadichvuUser::model()->findByAttributes(array('iduser'=>$_REQUEST['iduser'], 'iddichvu'=>$_REQUEST['iddichvu']));
			if($giauser != null){
				$giauser->delete();
			}
		}
		
		$this->redirect(array('listgiauser', 'iduser'=>$_REQUEST['iduser']));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Dichvu;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Dichvu']))
		{
			$model->attributes=$_POST['Dichvu'];
			$model->trangthai = 1;
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$criteria = new CDbCriteria();
		$criteria->compare('trangthai', 1);
		$var =Nhomdichvu::model()->findAll($criteria);
		$data['nhomdichvu'] = CHtml::listData($var, "id", "tennhom");
		$data['model'] = $model;
		$this->render('create',$data);
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Dichvu']))
		{
			$model->attributes=$_POST['Dichvu'];
			//if($model->save())
			 Dichvudao::update($model);
				$this->redirect(array('view','id'=>$model->id));
		}

		$var =Nhomdichvu::model()->findAll();
		$data['nhomdichvu'] = CHtml::listData($var, "id", "tennhom");
		$data['model'] = $model;
		$this->render('update',$data);
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	
	public function actionDelete($id)
	{
		//Dichvudao::delete($id);
		$model = Dichvu::model()->findByPK($id);
		$model->trangthai=0;
		$model->update();
		$this->redirect(array('index'));
	}
	
	public function actionXoa($id)
	{
		Dichvudao::delete($id);
		$this->redirect(array('index'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		/*
		$criteria = new CDbCriteria();
		$criteria->compare('trangthai',1);
		$Page = new CPagination(Dichvu::model()->count($criteria));
		//$Page->pageSize = Yii::app()->params['listPerPage'];
		$Page->pageSize = 25;
		$Page->applyLimit($criteria);		            
		$this->render('index', array(
		    'model' => Dichvu::model()->findAll($criteria),
		    'pages' => $Page
		));
	*/
		$criteria=new CDbCriteria;
		//$criteria->compare('trangthai',1);
		$model = Dichvu::model()->findAll($criteria);
		$this->render('index', array('model'=>$model));
		
		
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Dichvu('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Dichvu']))
			$model->attributes=$_GET['Dichvu'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Dichvu::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='dichvu-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	protected function checkvalidimei($listimei){
		$list = explode("\r\n", $listimei);
		//echo "<span>".$listimei. "</span>";die();
//print_r($list);die();
		$count = count($list);
		$result = array();
		$idx = 0;
		for($i=0;$i<$count;$i++)
		{
			if(strlen($list[$i])!=0 ){
				if(strlen($list[$i])!= 15 )
				{
					return false;
				}	
				if(!is_numeric($list[$i])){
					return false;
				}		
				$result[$idx] = $list[$i];
				$idx++;	
			}		
					
		}
		return $result;
	}
	
	public function actionMuaDichVu($id){
		$typemessage='';
		$message='';
		
		if(!isset($id)){
			$this->redirect('muadichvu2');
		}
		
		
		$imei ='';
		$dichvu = Dichvu::model()->findByPK($id);
		$iduser = UserUtils::getUserId();
		$cre = Credit::model()->findByAttributes(array('iduser'=>$iduser));
		$gia =$dichvu->gia;
		$giauser = GiadichvuUser::model()->findByAttributes(array('iduser'=>$iduser, 'iddichvu'=>$id));
		if($giauser != null ){
			$gia =$giauser->gia;
		}
			
		if(isset($_REQUEST['imei'])){
			$imei = $_REQUEST['imei'];
			$list = $this->checkvalidimei( $imei);
			if($list==false){
				$typemessage='error';
				$message="Imei nhập không đúng, quý khách vui lòng kiểm tra lại";
			}else{
				$cre = Credit::model()->findByAttributes(array('iduser'=>$iduser));
				if(count($list) * $gia > $cre->sodu){
					$typemessage='error';
					$message=" Bạn không đủ credit để đặt hàng, vui lòng nạp thêm vào tài khoản";
				}else{
				
					// trừ credit
					
					//$cre->sodu = $cre->sodu - (count($listImei) * $gia);
					//$cre->update();
					
					$currentdate =  DateUtils::getNow();
					foreach ($list as $item){
						$model = new Muadichvu;
						$model->iduser = $iduser;
						$model->ghichu = $_REQUEST['comment'];
						$model->noidung = $item;
						$model->iddichvu = $id;
						$model->gia = $gia;
						$model->ngaymua = $currentdate;
						$model->trangthai = 0;
						$model->save();
					}
					$user = User::model()->findByPK($iduser);
					$tongsotien = count($list) * $gia;
					// tru tien va gui mail tru tien
					Creditdao::truCredit($cre, $tongsotien, $user, $imei);
					// gui mail order
					EmailUtils::sendemailOrder($list,$dichvu, $gia, $user);
					Yii::app()->user->setId($user);
					$message=" Đặt hàng thành công, hệ thống sẽ thông báo qua E-mail sau khi đơn hàng được xử lí";
					$typemessage='success';
				}
			}
		Yii::app()->user->setFlash( $typemessage , $message);
		}
		$this->render('muadichvu', array('imei'=>$imei, 'dichvu'=> $dichvu, 'gia'=>$gia,'cre'=>$cre));
	}
	
	public function actionMuaDichVu2(){
		$typemessage='';
		$message='';
		$imei ='';
		$criteria = new CDbCriteria();
		$criteria->compare('trangthai',1);
		$items =  Dichvu::model()->findAll($criteria);
		$dichvu = new Dichvu;
		foreach ($items as $item){
			$dichvu = $item;
			break;
		}
		$iduser = UserUtils::getUserId();
		$id = $dichvu->id;
		if(isset($_POST['id'])){
			$id =$_POST['id'];
		}
		$dichvu = Dichvu::model()->findByPK($id);
		
		$gia =$dichvu->gia;
		$giauser = GiadichvuUser::model()->findByAttributes(array('iduser'=>$iduser, 'iddichvu'=>$id));
			if($giauser != null ){
				$gia =$giauser->gia;
			}
		$cre = Credit::model()->findByAttributes(array('iduser'=>$iduser));
		if(isset($_POST['imei']) && isset($_POST['id'])){
			$imei = $_POST['imei'];
			$list = $this->checkvalidimei( $imei);
			if($list==false){
				$typemessage='error';
				$message="Imei nhập không đúng, quý khách vui lòng kiểm tra lại";
			}else{
			
			$cre = Credit::model()->findByAttributes(array('iduser'=>$iduser));
			
			if(count($list) * $gia > $cre->sodu){
				$typemessage='error';
				$message="Bạn không đủ credit để đặt hàng, vui lòng nạp thêm vào tài khoản";
			}else{
			
				// trừ credit
				
				//$cre->sodu = $cre->sodu - (count($listImei) * $gia);
				//$cre->update();
				
				$currentdate =  DateUtils::getNow();
				foreach ($list as $item){
					$model = new Muadichvu;
					$model->iduser = $iduser;
					$model->noidung = $item;
					$model->iddichvu = $dichvu->id;
					$model->gia = $gia;
					$model->ngaymua = $currentdate;
					$model->trangthai = 0;
					$model->ghichu = $_REQUEST['comment'];
					$model->save();
					//print_r( $model->attributes);
				}
				//die();
				
				$user = User::model()->findByPK($iduser);
				$tongsotien = count($list) * $gia;
				// tru tien va gui mail tru tien
				Creditdao::truCredit($cre, $tongsotien, $user, $imei);
				// gui mail order
				EmailUtils::sendemailOrder($list,$dichvu, $gia, $user);
				
				Yii::app()->user->setId($user);
				Yii::app()->user->setId($user);
				$message=" Đặt hàng thành công, hệ thống sẽ thông báo qua E-mail sau khi đơn hàng được xử lí";
				$typemessage='success';
				}
			}
		Yii::app()->user->setFlash( $typemessage , $message);
		}
		//$nhomdichvu = Dichvudao::getlist(true);
		$criteria = new CDbCriteria();
		$criteria->order = 'uutien ASC';
		$criteria->compare('trangthai',1);
		$nhomdichvu = Nhomdichvu::model()->findAll($criteria); 
		
		$nhom = array();
		foreach ($nhomdichvu as $item) {
			$criteria = new CDbCriteria();
			$criteria->compare('trangthai',1);
			$criteria->compare('idnhomdichvu',$item->id);
			$criteria->order = 'uutien ASC';
			$idchvus = Dichvu::model()->findAll($criteria);
		    $nhom = array_merge($nhom, $idchvus);
		}
		$data['nhomdichvu'] = CHtml::listData( $nhom,'id','tendichvu','tbnhomdichvu.tennhom');
		$data['dichvu'] = $dichvu;
		$data['gia']=$gia;
		$data['cre']=$cre;
		$data['id']=$id;
		$this->render('muadichvu2', $data);
	
	}
	
	
	/**
	 * 
	 * Mua dich vu con kem so dien thoai
	 */
	public function actionMuaDichVu3(){
		$imei ='';
		$items =  Dichvu::model()->findAll();
		$dichvu = new Dichvu;
		foreach ($items as $item){
			$dichvu = $item;
			break;
		}
		$iduser = UserUtils::getUserId();
		$id = $dichvu->id;
		if(isset($_POST['id'])){
			$id =$_POST['id'];
		}
		$dichvu = Dichvu::model()->findByPK($id);
		
		$gia =$dichvu->gia;
		$giauser = GiadichvuUser::model()->findByAttributes(array('iduser'=>$iduser, 'iddichvu'=>$id));
			if($giauser != null ){
				$gia =$giauser->gia;
			}
		$cre = Credit::model()->findByAttributes(array('iduser'=>$iduser));
		if(isset($_POST['imei']) && isset($_POST['id']) && isset($_POST['sodienthoai'])){
			$imei = $_POST['imei'];
			$list = explode("\n", $imei);
			$cre = Credit::model()->findByAttributes(array('iduser'=>$iduser));
			
			if(count($list) * $gia > $cre->sodu){
				echo "Bạn không đủ credit order, vui lòng nạp thêm tài khoản";
				die();
			}
			
			// trừ credit
			
			//$cre->sodu = $cre->sodu - (count($listImei) * $gia);
			//$cre->update();
			
			$currentdate =  DateUtils::getNow();
			foreach ($list as $item){
				$model = new Muadichvu;
				$model->iduser = $iduser;
				$model->noidung = $item;
				$model->iddichvu = $dichvu->id;
				$model->gia = $gia;
				$model->ngaymua = $currentdate;
				$model->trangthai = 0;
				$model->sodienthoai = $_POST['sodienthoai'];
				
				$model->save();
			}
			
			$user = User::model()->findByPK($iduser);
			$tongsotien = count($list) * $gia;
			// tru tien va gui mail tru tien
			Creditdao::truCredit($cre, $tongsotien, $user, $imei);
			// gui mail order
			EmailUtils::sendemailOrder($list, $gia, $user);
			
			Yii::app()->user->setId($user);
			$this->redirect(array('history'));
		}
		
		$nhomdichvu = Dichvudao::getlist(true);
		$data['nhomdichvu'] = CHtml::listData( $nhomdichvu,'id','tendichvu');
		$data['dichvu'] = $dichvu;
		$data['gia']=$gia;
		$data['cre']=$cre;
		$this->render('muadichvu3', $data);
	
	}
	
	/*Json autocomplete Create.php*/
	public function actionSuggestDichvu() {
		$criteria = new CDbCriteria;
		$criteria->select = array('id', 'tendichvu');
	
		$criteria->addSearchCondition('tendichvu',  strtoupper( $_GET['term']) ) ;
		$criteria->limit = 15;
		$data = Dichvu::model()->findAll($criteria);
	
		$arr = array();
	
		foreach ($data as $item) {
			 
			$arr[] = array(
					'id' => $item->id,
					'value' => $item->tendichvu,
					'label' => $item->tendichvu,
			);
		}
	
		echo CJSON::encode($arr);
	
	}
	
	
	public function actionHistory(){
		$model = new Muadichvu('search');
		if(isset($_REQUEST['Muadichvu'])){
			$model->attributes = $_REQUEST['Muadichvu'];
		}
		$model->iduser=UserUtils::getUserId();
		$this->render('history', array('model'=>$model));
	}
	
	public function actionOrderAdmin(){
		if(isset($_REQUEST['orders']))
		{
			$arr = $_REQUEST['orders'];
			$request = explode(',', $arr);
			$comment = '';
			if(isset($_REQUEST['comment'])){
				$comment = $_REQUEST['comment'];
			}
			Dichvudao::changeState($_REQUEST['ordertype'],$request, $comment);
		}
		
		if(isset($_REQUEST['type'])){
			switch($_REQUEST['type']){
				case "order":
					 $listorders = Dichvudao::listOrder(0);
					$this->render('_orders' , array('listorders' => $listorders));
					break;
				case "pendding1":
					$this->render('_orderpendding', array('trangthai'=>1));
					break;
				case "pendding2":
					$this->render('_orderpendding', array('trangthai'=>12));
					break;
				case "done":
					$listunlock = Dichvudao::listOrder(2);
					$this->render('_orderunlock', array('listunlock'=>$listunlock));
					break;
				case "refund":
					$this->render('_orderrefund');
					break;
			}
		}else{
			 $listorders = Dichvudao::listOrder(0);
			$this->render('_orders' , array('listorders' => $listorders));
		}
	}
	
	public function actionExportOrder(){
		
    $data = Muadichvu::model()->findAll();
    $filename = 'orders-'. DateUtils::getNow();
    if(isset($_REQUEST['trangthai'])){
    	$criteria = new CDbCriteria();
		$criteria->order = 'iddichvu ASC, ngaycapnhat DESC, ngaymua DESC';
		$criteria->compare('trangthai',$_REQUEST['trangthai']);
    	$data = Muadichvu::model()->findAll($criteria);
    	switch($_REQUEST['trangthai']){
    		case 0:
    			 $filename = 'orders-'. DateUtils::getNow();
    			 break;
    		 case 1:
	    		 $filename = 'pendding-'. DateUtils::getNow();
	    		 break;
    		 case 2:
	    		 $filename = 'unlocked-'. DateUtils::getNow();
	    		 break;
    		 case 3:
	    		 $filename = 'refund-'. DateUtils::getNow();
	    		 break;
    	}
    }
    
    for($i=0; $i < count($data); $i++){
    	$data[$i]->iduser = $data[$i]->tbuser->username;
    	$data[$i]->iddichvu = $data[$i]->tbdichvu->tendichvu;
    }
    
	Yii::import('application.extensions.phpexcel.JPhpExcel');
	$xls = new JPhpExcel('UTF-8', false, 'My Test Sheet');
	$xls->addArray($data);
	$xls->generateXML($filename);
	}
	
	public function actionGia(){
		$model = new GiadichvuUser;
		if(isset($_POST['GiadichvuUser'])){
			$model->attributes = $_POST['GiadichvuUser'];
			if($model->validate()){
				GiaDichvuUserdao::setGia($model);
				$this->redirect(array('listgiauser', 'iduser'=>$model->iduser));
			}
		}
		$user =User::model()->findAll();
		$data['users'] = CHtml::listData($user, "id", "username");
		$dichvu =Dichvu::model()->findAll();
		$data['dichvu'] = CHtml::listData($dichvu, "id", "tendichvu");
		$data['model'] = $model;
		$this->render('gia', $data);
	}
	
	public function actionListGiaUser(){
		$iduser = $_REQUEST['iduser'];
		$model = GiaDichvuUserdao::getlistByidUser($iduser);
		$user = User::model()->findByPK($iduser);
		$data['user'] = $user;
		$data['model'] = $model;
		$this->render('listgiauser', $data);
	}
	
	public function actionTraCode($id){
		$model = Muadichvu::model()->findByPK($id);
		if(isset($_REQUEST['Muadichvu'])){
			$dichvu = new Muadichvu;
			$dichvu->attributes = $_REQUEST['Muadichvu'];
			Dichvudao::traCode($model, $dichvu->ketqua);
			$this->redirect(array('orderadmin'));
		}
		
		$this->render('tracode', array("model"=>$model));
	}
	
	//autocomplete action
	
	
	//json click chon combobox	
	public function actiongetJson() /* ajax function */
	{		
		$event = Dichvu::model()->findByPk($_POST['id']);		
		$gia = $event->gia;
		$giauser = GiadichvuUser::model()->findByAttributes(array('iddichvu'=>$_POST['id'], 'iduser'=>$_POST['iduser']));
		if($giauser != null){
			$gia = $giauser->gia;
		}
		$return_array = array(
				'data'=>array(
						'gia'=>$gia,
						'thoigian'=>$event->thoigian,	
						'id'=>$event->id,
						'ghichu'=>$event->ghichu,
				),
		);
		echo json_encode($return_array);
	}
	
	public function actionQuickAccess(){
		$this->render('quickaccess');
	}
	
	public function actionHistoryUser(){
		$username = $_REQUEST['username'];
		$data['chitietnapcredit'] = new Chitietnapcredit('search');
		$data['chitietnapcredit']->username = $username;
		if(isset($_REQUEST['Chitietnapcredit'])){
			$data['chitietnapcredit']->attributes = $_REQUEST['Chitietnapcredit'];
		}
		$data['username'] = $username;
		$this->render('historyuser', $data);
	}
	
	public function actionHistoryUserAdmin(){
		
		$model = new User;
		if(isset($_POST['User'])){
			$model->attributes = $_POST['User'];
			$this->redirect(array('historyuser', 'username'=>$model->username));
		}else{
			$data['model'] = $model;
			$data['lichsudangnhap'] = new Tblog('search');
			if(isset($_POST['Tblog'])){
				$data['lichsudangnhap']->attributes = $_POST['Tblog'];
			}
			$this->render('historyuseradmin', $data);
		}
	}
	
	public function actionCompleteUser() {
		$criteria = new CDbCriteria;
		$criteria->select = array('id', 'username');
	
		$criteria->addSearchCondition('username',  strtoupper( $_GET['term']) ) ;
		$criteria->limit = 15;
		$data = User::model()->findAll($criteria);
	
		$arr = array();
	
		foreach ($data as $item) {
			 
			$arr[] = array(
					'id' => $item->id,
					'value' => $item->username,
					'label' => $item->username,
			);
		}
	
		echo CJSON::encode($arr);
	
	}
}
